package com.bridgetree.jubaocrm.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.JsonObjectPostRequest;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshBase.OnRefreshListener;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshListView;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.LoginInterface;
import com.bridgetree.jubaocrm.util.Projects;

public class SearchProjectActivity extends Activity implements OnClickListener{
	private EditText searchEt;
	private PullToRefreshListView firstcategoryXM = null;
	private ListView actualListView3 = null;
	private String userName;
	private String passWord;
	private SharedPreferences prefs;
	private List<Projects> my_projects =new ArrayList<Projects>() ;
	PageProjectAdapter mRuAdapter3;
	private int pageIndex;
	private LoginInterface mLoginInterface;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		searchEt=(EditText) findViewById(R.id.search_edit);
		RelativeLayout backView=(RelativeLayout) findViewById(R.id.xm_12_RelativeLayout_back);
		Button searchbtn=(Button) findViewById(R.id.search_btn);
		searchbtn.setOnClickListener(this);
		backView.setEnabled(true);
		backView.setOnClickListener(this);
		prefs = PreferenceManager
				.getDefaultSharedPreferences(SearchProjectActivity.this);
		userName = prefs.getString(Contents.KEY_PERSONAL_USERNAME, "");
		passWord = prefs.getString(Contents.KEY_PERSONAL_PASSWORD, "");
		Intent intent = getIntent();
		if (intent.getExtras() != null) {
			mLoginInterface = (LoginInterface) intent.getExtras()
			.getSerializable("LoginInterface");
		}
		initRefreshList();
	}
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.search_btn:
			String searchKeyword=searchEt.getText().toString();
			getJSONByVolley(userName,passWord,searchKeyword);
			break;
		case R.id.xm_12_RelativeLayout_back:
			this.finish();
			break;
		}
	}
	private int pageIndexma = 1;
	PageMyAnnouncementAdapter mRuAdapter2;
	private int scrollTopBottomma = 0;
	private void initRefreshList() {
		// TODO Auto-generated method stub
		firstcategoryXM=(PullToRefreshListView)findViewById(R.id.firstcategoryXM);
		firstcategoryXM.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				if(mRuAdapter3!=null)
					mRuAdapter3.notifyDataSetChanged();
				if(firstcategoryXM!=null)
					firstcategoryXM.onRefreshComplete();
				getJSONByVolley(userName,passWord,searchEt.getText().toString());
			}
		});

		firstcategoryXM.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
			}
		});
		actualListView3 = firstcategoryXM.getRefreshableView();

		//		List<HashMap<String, Object>> proInfoListData = new ArrayList<HashMap<String,Object>>();
		//		HashMap<String, Object> map =null;
		//		
		//		map =new HashMap<String, Object>();
		//		map.put("tv", "2015年度窗体广告");
		//		proInfoListData.add(map);
		if(my_projects != null){
			mRuAdapter3 = new PageProjectAdapter(this,my_projects);
			actualListView3.setAdapter(mRuAdapter3);
		}
	}
	
	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(this).setTitle(title)
		.setMessage(content).setPositiveButton("确定",new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (content != null && content.trim().equals("用户不存在")) {
					// finish();
				}
				if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
					LoginUtil.executeLoginFaild(SearchProjectActivity.this);
				}

			}
		}).show();
	}
	/**
	 * 项目刷新
	 */
	private void getJSONByVolley(final String username,String password,String searchKeyword) {
		Network mNetword = new Network(this);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else if (username.equals("") || password.equals("")) {
			openDailog("输入提示", "账号或密码不能为空！");
		} else {
			HashMap<String, String> mMap = new HashMap<String, String>();
			mMap.put("user_id", mLoginInterface.getUser_id());
			mMap.put("token", mLoginInterface.getToken());
			mMap.put("key", searchKeyword);
			mMap.put("validation", CRMUserBaseInfo.kValication);
			
			String URL = Network.API_DOMAIN + "/search";

			final ProgressDialog progressDialog = ProgressDialog.show(this,
					"请稍等", "...Loading...");
			RequestQueue requestQueue = Volley.newRequestQueue(this);
			JsonObjectPostRequest jsonObjectPostRequest = new JsonObjectPostRequest(
					URL, new Response.Listener<JSONObject>() {

						@Override
						public void onResponse(JSONObject response) {
							try {
								if (progressDialog.isShowing()
										&& progressDialog != null) {
									progressDialog.dismiss();
								}
								String user_id = "";
								String token = "";
								Log.e("wop",
										" response = " + response.toString());
								if (!response.isNull("my_projects")) {
									org.json.JSONArray jsonArr;
									my_projects = new ArrayList<Projects>();
									jsonArr = response
									.getJSONArray("my_projects");
									if (jsonArr.length() > 0) {
										for (int i = 0; i < jsonArr.length(); i++) {
											Projects my_project = new Projects();
											JSONObject jsonObj2 = jsonArr
											.getJSONObject(i);
											if (!jsonObj2.isNull("is_approved")) {
												boolean is_approved = Boolean.valueOf(jsonObj2
														.getString("is_approved"));
												my_project
												.setIs_approved(is_approved);
											}
											if (!jsonObj2.isNull("client_id")) {
												String client_id = jsonObj2
												.getString("client_id");
												my_project
												.setClient_id(client_id);
											}
											if (!jsonObj2
													.isNull("project_name")) {
												String project_name = jsonObj2
												.getString("project_name");
												my_project
												.setProject_name(project_name);
											}
											if (!jsonObj2.isNull("project_id")) {
												String project_id = jsonObj2
												.getString("project_id");
												my_project
												.setProject_id(project_id);
											}
											if (!jsonObj2
													.isNull("project_status")) {
												String project_status = jsonObj2
												.getString("project_status");
												my_project
												.setProcess_status(project_status);
											}
											my_project.setUser_id(mLoginInterface.getUser_id());
											my_project.setToken(mLoginInterface.getToken());
											my_projects.add(my_project);
										}
									}
//									mLoginInterface.setMy_projects(my_projects);
								}
//								if (!response.isNull("fullname")) {
//									String fullname = response.get("fullname")
//									.toString();
//									mLoginInterface.setFullname(fullname);
//								}
								if (!response.isNull("errors")) {
									String errors = response.get("errors")
									.toString();
									if (errors.equals("[]")) {
//										prefs.edit().putString(Contents.KEY_PERSONAL_USERNAME, userName).commit();
//										prefs.edit().putString(Contents.KEY_PERSONAL_PASSWORD, passWord).commit();
//										prefs.edit().putString(Contents.KEY_PERSONAL_LOGIN_USEID, mLoginInterface.getUser_id()).commit();
//										prefs.edit().putString(Contents.KEY_PERSONAL_LOGIN_TAKEN,  mLoginInterface.getToken()).commit();
//										prefs.edit().putBoolean(Contents.KEY_PERSONAL_LOGIN_STATE, true).commit();
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response
											.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr
												.length(); i++) {
													JSONObject jsonObj2 = jsonArr
													.getJSONObject(i);
													if (!jsonObj2
															.isNull("desc")) {
														String desc = jsonObj2
														.getString("desc");
														openDailog("失败提示",
																desc);
														mLoginError
														.setDesc(desc);
													}
													if (!jsonObj2
															.isNull("value")) {
														String value = jsonObj2
														.getString("value");
														mLoginError
														.setValue(value);
													}
												}
											}
//											mLoginInterface
//											.setErrors(mLoginError);
										}
									}
								}
//								my_projects = mLoginInterface.getMy_projects();
								mRuAdapter3 = new PageProjectAdapter(SearchProjectActivity.this,
										my_projects);
								mRuAdapter3.notifyDataSetChanged();
								actualListView3.setAdapter(mRuAdapter3);
								if (firstcategoryXM != null) {
									firstcategoryXM.onRefreshComplete();
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							ProgressDialogUtil.dissmis(progressDialog);
							Toast.makeText(SearchProjectActivity.this, "网络未连接！",
									Toast.LENGTH_LONG).show();
						}
					}, mMap);
			requestQueue.add(jsonObjectPostRequest);
		}

	}
}
